<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="单据编号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchasing:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchasing:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchasing:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchasing:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商" align="center" prop="supplier">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pru_shop" :value="scope.row.supplier"/>
        </template>
      </el-table-column>
      <el-table-column label="单据编号" align="center" prop="orderNumber" />
      <el-table-column label="商品信息" align="center" prop="merchandiseNews" width="300" />
      <el-table-column label="单据日期" align="center" prop="orderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作员" align="center" prop="operator" />
      <el-table-column label="总金额" align="center" prop="aggregateAmount" />
      <el-table-column label="定金" align="center" prop="earnest" />
      <el-table-column label="状态" align="center" prop="orderState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pru_order_state" :value="scope.row.orderState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleUpdateOrderState(scope.row)"
            v-hasPermi="['purchasing:order:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchasing:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchasing:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置对话框 -->
    <el-dialog title="添加采购订单" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form"  label-width="100px" :inline="true" style="width: 100%;padding: 20px">
        <el-form-item label="供应商" prop="supplier">
          <el-select v-model="form.supplier" placeholder="请选择供应商">
            <el-option
              v-for="dict in dict.type.pru_shop"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        &emsp;&emsp;&emsp;
        <el-form-item>
          <el-button icon="el-icon-search" @click="showGoodsListDialog" size="mini">选择商品</el-button>
        </el-form-item>

        <div style="border-top: 1px solid #e0e0e0;margin-top:20px;margin-bottom:20px" @change="getTotal"></div>

        <el-table   :data="selectGoodsList"  >
          <el-table-column label="名字" prop="name"  />
          <el-table-column label="规格" prop="spec"  />
          <el-table-column label="型号" prop="model"  />
          <el-table-column label="颜色" prop="colour"  />
          <el-table-column label="单位" prop="unit"  />
          <el-table-column label="价格" prop="price"  />
          <el-table-column label="数量" prop="number"  >
            <template slot-scope="scope">
              <el-input v-model="scope.row.number" @ placeholder="" size="mini" @change="getTotal" style="width: 100px"/>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <div style="width: 100%">
          <el-input  type="textarea" v-model="form.remark" placeholder="订单备注" />
        </div>
        <br/>
        <el-form-item label="结算账户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择结算账户">
            <el-option
              v-for="dict in dict.type.pru_user"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总额" prop="aggregateAmount">
          <el-input v-model="form.aggregateAmount"  placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠金额" prop="discounts">
          <el-input v-model="form.discounts" value="0" @change="getTotal2" placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠后金额" prop="discountsAmount">
          <el-input v-model="form.discountsAmount"  placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="支付定金" prop="earnest">
          <el-input v-model="form.earnest" placeholder="" size="mini"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定添加</el-button>
        <el-button type="primary" @click="submitForm2">添加并审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择商品的弹窗 -->
    <el-dialog title="选择要采购的商品" :visible.sync="goodsListOpen" width="1000px" append-to-body>

      <el-table  ref="goodsTable"  :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名字" prop="name"  />
        <el-table-column label="规格" prop="spec"  />
        <el-table-column label="型号" prop="model"  />
        <el-table-column label="颜色" prop="colour" />
        <el-table-column label="单位" prop="unit"  />
        <el-table-column label="价格" prop="price"  />
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="goodsListOpen = false">确定选择</el-button>
        <el-button @click="goodsListDialogCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder ,changeOrderState} from "@/api/purchasing/order";
import { listDetails, getDetails, delDetails, addDetails, updateDetails ,getDetailsByOrderNUmber} from "@/api/purchasing/details";

export default {
  name: "Order",
  dicts: ['pru_user', 'pru_shop', 'pru_order_state'],

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      //商品列表
      goodsList: [
        {id:1,code:"G001",name:"苹果手机-假数据",spec:"32G",model:"IPhone14",colour:"红色",unit:"个",price:200,number:1},
        {id:2,code:"G002",name:"苹果手机-假数据",spec:"64G",model:"IPhone14",colour:"红色",unit:"个",price:200,number:1},
        {id:3,code:"G003",name:"小米",spec:"64G",model:"mi14",colour:"白色",unit:"个",price:300,number:1}
      ],
      //选中的商品
      selectGoodsList:[],
      //第一个弹窗
      open:false,
      //第二个弹窗
      goodsListOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplier: null,
        orderNumber: null,
        merchandiseNews: null,
        orderTime: null,
        operator: null,
        aggregateAmount: null,
        earnest: null,
        orderState: null,
        userId: null,
        discounts: null,
        discountsAmount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //计算优惠后总价
    getTotal2(){
      this.form.discountsAmount=0;
      if(this.form.discounts==0){
        this.form.discountsAmount=this.form.aggregateAmount
      }else {

        this.form.discountsAmount=this.form.aggregateAmount-this.form.discounts
      }
      return this.form.discountsAmount
    },
    // 计算总价
    getTotal(){
      this.form.aggregateAmount = 0;
      for(var i=0;i<this.selectGoodsList.length;i++){


        this.form.aggregateAmount+=this.selectGoodsList[i].price*this.selectGoodsList[i].number

      }
      return this.form.aggregateAmoun
    },

    goodsListDialogCancel(){
      this.goodsListOpen = false;
      this.selectGoodsList = [];
      this.$refs.goodsTable.clearSelection();
    },
    // 多选框选中数据
    handleGoodsSelectionChange(selection){
      this.selectGoodsList = selection;
      this.getTotal();

    },
    showGoodsListDialog(){
      this.goodsListOpen = true;
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        oderId: null,
        supplier: null,
        orderNumber: null,
        merchandiseNews: null,
        orderTime: null,
        operator: null,
        aggregateAmount: null,
        earnest: 0,
        orderState:0,
        userId: null,
        discounts: 0,
        discountsAmount: 0,
        goodsList:[],
        selectGoodsList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.oderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectGoodsList=[];
      this.open = true;
      this.title = "添加采购订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const oderId = row.oderId || this.ids
      getDetailsByOrderNUmber(row.orderNumber).then(response => {
        this.selectGoodsList = response.data;
      });
      getOrder(oderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购订单";
      });
    },
    /** 确定添加 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.oderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.goodsList=this.selectGoodsList;

            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 审核按钮操作 */
    handleUpdateOrderState(row) {
      this.reset();
      const oderId = row.oderId || this.ids
      changeOrderState(oderId).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.getList();
      });


    },
    /** 确定添加并审核 */
    submitForm2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
           this.form.orderState=1;
           this.form.goodsList=this.selectGoodsList;
           addOrder(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
            });
          }

      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const oderIds = row.oderId || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + oderIds + '"的数据项？').then(function() {
        return delOrder(oderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchasing/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
